from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_socketio import SocketIO
import os
from dotenv import load_dotenv
from datetime import datetime

# 載入環境變數
load_dotenv()

# 初始化扩展
db = SQLAlchemy()
login_manager = LoginManager()
socketio = SocketIO()

# 全局房間存儲（模擬數據）
rooms = {
    # 'test001': {
    #     'player1': {'name': 'Player1', 'ws': None},
    #     'player2': None,
    #     'status': 'waiting',
    #     'createdAt': '2024-01-01T10:00:00Z'
    # },
    # 'test002': {
    #     'player1': {'name': 'Player1', 'ws': None},
    #     'player2': {'name': 'Player2', 'ws': None},
    #     'status': 'playing',
    #     'createdAt': '2024-01-01T09:30:00Z'
    # },
    # 'test003': {
    #     'player1': None,
    #     'player2': None,
    #     'status': 'waiting',
    #     'createdAt': '2024-01-01T11:00:00Z'
    # }
}

def create_app():
    # 初始化应用
    app = Flask(__name__)

    # 数据库配置
    DB_HOST = 'mysql2.sqlpub.com'
    DB_PORT = 3307
    DB_USER = 'guojiahao'
    DB_PASSWORD = 'ra4RYCCAQqumn8pr'
    DB_NAME = 'bighomework123'

    app.config['SQLALCHEMY_DATABASE_URI'] = f'mysql+pymysql://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}'
    app.config['SECRET_KEY'] = 'your-secure-key-here'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    # 初始化扩展
    db.init_app(app)
    login_manager.init_app(app)
    login_manager.login_view = 'auth.login'
    socketio.init_app(app)

    # 注册蓝图
    from .auth import auth_bp
    from .admin import admin_bp
    from .user import user_bp

    app.register_blueprint(auth_bp)
    app.register_blueprint(admin_bp)
    app.register_blueprint(user_bp)

    # 房間查詢 API 端點
    @app.route('/api/rooms')
    def query_room():
        try:
            room_id = request.args.get('roomId')
            print(f'[API] 查詢房間: {room_id}')
            
            if not room_id:
                return jsonify({
                    'success': False,
                    'message': '請提供房間ID'
                }), 400
            
            # 檢查房間是否存在
            room = rooms.get(room_id)
            if not room:
                return jsonify({
                    'success': False,
                    'message': '房間不存在'
                }), 404
            
            # 計算玩家數量
            player_count = 0
            if room.get('player1'):
                player_count += 1
            if room.get('player2'):
                player_count += 1
            
            # 確定房間狀態
            status = 'waiting'
            if player_count == 0:
                status = 'empty'
            elif player_count >= 2:
                status = 'playing'
            else:
                status = 'waiting'
            
            # 返回房間信息
            room_info = {
                'roomId': room_id,
                'status': status,
                'playerCount': player_count,
                'maxPlayers': 2,
                'createdAt': room.get('createdAt', '2024-01-01T00:00:00Z')
            }
            
            print(f'[API] 房間查詢成功:', room_info)
            return jsonify({
                'success': True,
                'data': room_info
            })
            
        except Exception as error:
            print(f'[API] 房間查詢錯誤: {error}')
            return jsonify({
                'success': False,
                'message': '服務器內部錯誤'
            }), 500

    # 獲取所有房間列表的 API 端點
    @app.route('/api/rooms/list')
    def list_rooms():
        try:
            print('[API] 獲取房間列表')
            print(f'[API] 當前房間數據: {rooms}')
            
            room_list = []
            for room_id, room in rooms.items():
                # 計算玩家數量
                player_count = 0
                if room.get('player1'):
                    player_count += 1
                if room.get('player2'):
                    player_count += 1
                
                # 確定房間狀態
                status = 'waiting'
                if player_count == 0:
                    status = 'empty'
                elif player_count >= 2:
                    status = 'playing'
                else:
                    status = 'waiting'
                
                room_info = {
                    'roomId': room_id,
                    'status': status,
                    'playerCount': player_count,
                    'maxPlayers': 2,
                    'createdAt': room.get('createdAt', '2024-01-01T00:00:00Z')
                }
                room_list.append(room_info)
                print(f'[API] 房間 {room_id}: 玩家數={player_count}, 狀態={status}')
            
            print(f'[API] 房間列表查詢成功，共 {len(room_list)} 個房間')
            print(f'[API] 房間詳情: {room_list}')
            return jsonify({
                'success': True,
                'data': room_list
            })
            
        except Exception as error:
            print(f'[API] 房間列表查詢錯誤: {error}')
            return jsonify({
                'success': False,
                'message': '服務器內部錯誤'
            }), 500

    # 健康檢查端點
    @app.route('/health')
    def health_check():
        return jsonify({'status': 'ok', 'message': 'Flask server is running'})

    # 創建房間 API 端點
    @app.route('/api/rooms/create', methods=['POST'])
    def create_room():
        try:
            data = request.get_json()
            room_id = data.get('roomId') if data else None
            
            if not room_id:
                return jsonify({
                    'success': False,
                    'message': '請提供房間ID'
                }), 400
            
            # 檢查房間是否已存在
            if room_id in rooms:
                return jsonify({
                    'success': False,
                    'message': '房間已存在'
                }), 409
            
            # 創建新房間
            current_time = datetime.now().isoformat() + 'Z'
            
            rooms[room_id] = {
                'player1': None,
                'player2': None,
                'status': 'waiting',
                'createdAt': current_time
            }
            
            print(f'[API] 房間創建成功: {room_id}')
            return jsonify({
                'success': True,
                'data': {
                    'roomId': room_id,
                    'status': 'waiting',
                    'playerCount': 0,
                    'maxPlayers': 2,
                    'createdAt': rooms[room_id]['createdAt']
                }
            })
            
        except Exception as error:
            print(f'[API] 房間創建錯誤: {error}')
            return jsonify({
                'success': False,
                'message': '服務器內部錯誤'
            }), 500

    # 加入房間 API 端點
    @app.route('/api/rooms/join', methods=['POST'])
    def join_room():
        try:
            data = request.get_json()
            room_id = data.get('roomId') if data else None
            player_name = data.get('playerName', 'Player') if data else 'Player'
            
            if not room_id:
                return jsonify({
                    'success': False,
                    'message': '請提供房間ID'
                }), 400
            
            # 檢查房間是否存在
            if room_id not in rooms:
                return jsonify({
                    'success': False,
                    'message': '房間不存在'
                }), 404
            
            room = rooms[room_id]
            
            # 檢查房間是否已滿
            if room['player1'] and room['player2']:
                return jsonify({
                    'success': False,
                    'message': '房間已滿'
                }), 409
            
            # 加入房間
            if not room['player1']:
                room['player1'] = {'name': player_name, 'ws': None}
            elif not room['player2']:
                room['player2'] = {'name': player_name, 'ws': None}
                room['status'] = 'playing'
            
            print(f'[API] 玩家 {player_name} 加入房間 {room_id}')
            return jsonify({
                'success': True,
                'data': {
                    'roomId': room_id,
                    'status': room['status'],
                    'playerCount': (1 if room['player1'] else 0) + (1 if room['player2'] else 0),
                    'maxPlayers': 2,
                    'createdAt': room['createdAt']
                }
            })
            
        except Exception as error:
            print(f'[API] 加入房間錯誤: {error}')
            return jsonify({
                'success': False,
                'message': '服務器內部錯誤'
            }), 500

    # 加载用户
    @login_manager.user_loader
    def load_user(user_id):
        from .models import User
        return db.session.get(User, int(user_id))

    return app

if __name__ == '__main__':
    app = create_app()
    with app.app_context():
        db.create_all()
    socketio.run(app, host='0.0.0.0', debug=True)